<template>
    <div class="app-container">
      <el-main class="formC">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="智能识别" style="position: relative">
            <el-input type="textarea" v-model="consigneeText" :rows="6" resize="none" placeholder="请粘贴或者输入完整信息，点击识别将自动为您填入信息，格式为：XXX省XXX市XXX区县XXXXXX"></el-input>
            <el-button class="consignee" type="primary" size="mini" @click="parseCnPostConsignee" icon="el-icon-thumb">识别</el-button>
          </el-form-item>
          <el-row>
            <el-col :span="16">
              <el-form-item label="资产状态" prop="assetStatus">
                <el-select v-model="form.assetStatus" placeholder="请选择资产状态" clearable style="width: 100%">
                  <el-option
                    v-for="dict in dict.type.asset_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="自定义编号" prop="assetCustomNum">
                <el-input v-model="form.assetCustomNum" :disabled="type == 'edit'" clearable placeholder="自定义编号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="资产名称" prop="assetName">
            <el-input v-model="form.assetName" :disabled="type == 'edit'" clearable placeholder="资产名称" />
          </el-form-item>
          <el-form-item label="资产地点" required>
            <el-row style="display: flex;">
              <el-form-item prop="assetAddressProvince">
                <el-select v-model="form.assetAddressProvince" disabled @change="getCity" placeholder="请选择省份" style="width: 160px">
                  <el-option
                    v-for="pro in proCityList"
                    :key="pro.code"
                    :label="pro.name"
                    :value="pro.name"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="assetAddressCity">
                <el-select v-model="form.assetAddressCity" disabled @change="getArea" placeholder="请选择市" style="width: 160px">
                  <el-option
                    v-for="city in cityLsit"
                    :key="city.code"
                    :label="city.name"
                    :value="city.name"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="assetAddressDistrict">
                <el-select v-model="form.assetAddressDistrict" clearable placeholder="请选择区" style="width: 160px">
                  <el-option
                    v-for="area in areaList"
                    :key="area.code"
                    :label="area.name"
                    :value="area.name"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="assetAddress" style="flex: 1">
                <el-input v-model="form.assetAddress" clearable placeholder="资产地址" />
              </el-form-item>
            </el-row>
            <el-row style="margin-top: 20px">
              <el-form-item prop="assetLon">
                <bmap :pointLonLat="point" @clickAddress="clickAddress"></bmap>
              </el-form-item>
            </el-row>
          </el-form-item>
          <el-row>
            <el-col :span="16">
              <el-form-item label="门牌" required>
                <el-row style="display: flex;">
                  <el-form-item style="flex: 1" label="" prop="assetDoorNum">
                    <el-input v-model="form.assetDoorNum" clearable placeholder="" >
                      <template slot="append">号</template>
                    </el-input>
                  </el-form-item>
                  <el-form-item style="flex: 1;margin-left: 10px" label="" prop="assetUnitNum">
                    <el-input v-model="form.assetUnitNum" clearable placeholder="">
                      <template slot="append">单元</template>
                    </el-input>
                  </el-form-item>
                  <el-form-item style="flex: 1;margin-left: 10px" label="" prop="assetRoomNum">
                    <el-input v-model="form.assetRoomNum" clearable placeholder="" >
                      <template slot="append">室</template>
                    </el-input>
                  </el-form-item>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="房屋类型" prop="assetHouseType">
                <el-select v-model="form.assetHouseType" style="width: 100%" clearable placeholder="请选择房屋类型">
                  <el-option
                    v-for="dict in dict.type.asset_house_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="资产面积" prop="assetArea">
                <el-input v-model="form.assetArea" clearable placeholder="资产面积">
                  <template slot="append">㎡</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item style="width: 100%" label="建成年代" prop="assetEstablishDate">
                <el-date-picker clearable
                                style="width: 100%"
                                v-model="form.assetEstablishDate"
                                type="year"
                                value-format="yyyy"
                                placeholder="建成年代">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="产权年限" prop="assetOwnershipLength">
                <el-select v-model="form.assetOwnershipLength" style="width: 100%" placeholder="产权年限" clearable>
                  <el-option
                    v-for="dict in dict.type.age_limit"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item label="产权单位" prop="assetPropertyUnit">
                <el-select v-model="form.assetPropertyUnit" placeholder="产权单位" style="width: 100%" clearable>
                  <el-option
                    v-for="dict in dict.type.property_unit"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="账面原值" prop="assetOriginalValue">
                <el-input v-model="form.assetOriginalValue" type="number" placeholder="账面原值" >
                  <template slot="append">万元</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="图片上传" prop="assetImg">
              <ImageUpload v-model="form.assetImg" :limit="10"></ImageUpload>
            </el-form-item>
          </el-row>
        </el-form>
      </el-main>
      <el-footer style="text-align: center">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="reset">重 置</el-button>
      </el-footer>
    </div>
</template>

<script>
  import {proCityList} from '@/utils/china'
  import {addAssetInfo, getAssetInfo, updateAssetInfo, copyAssetInfo } from '@/api/business/assetInfo'
  import bmap from '@/components/bmap'
  export default {
    name: "assetInfoAdd",
    components: {bmap},
    dicts: ['asset_house_type', 'asset_status', 'screen_asset_area', 'property_unit', 'asset_house_type', 'age_limit'],
    data() {
      return {
        proCityList: proCityList,
        cityLsit: [],
        areaList: [],
        // 表单参数
        form: {
        },
        consigneeText: '',
        // 表单校验
        rules: {
          assetName: [
            { required: true, message: "资产名称不能为空", trigger: "blur" }
          ],
          // assetCustomNum: [
          //   { required: true, message: "自定义编号不能为空", trigger: "blur" }
          // ],
          assetAddressProvince: [
            { required: true, message: "请选择资产所在省份", trigger: "change" }
          ],
          assetAddressCity: [
            { required: true, message: "请选择资产所在城市", trigger: "change" }
          ],
          assetAddressDistrict: [
            { required: true, message: "请选择资产所在区县", trigger: "change" }
          ],
          assetAddress: [
            { required: true, message: "资产地址不能为空", trigger: "change" }
          ],
          assetLon: [
            { required: true, message: "请在地图上选点", trigger: "change" }
          ],
          assetDoorNum: [
            { required: true, message: "门牌号不能为空", trigger: "blur" }
          ],
          assetHouseType: [
            { required: true, message: "请选择房屋类型", trigger: "change" }
          ],
          assetArea: [
            { required: true, message: "资产面积不能为空", trigger: "blur" }
          ],
          assetEstablishDate: [
            { required: true, message: "请选择建成年代", trigger: "blur" }
          ],
          assetOwnershipLength: [
            { required: true, message: "请选择产权年限", trigger: "blur" }
          ],
          assetPropertyUnit: [
            { required: true, message: "请选择产权单位", trigger: "blur" }
          ],
          assetStatus: [
            { required: true, message: "请选择资产状态", trigger: "change" }
          ],
          assetOriginalValue: [
            { required: true, message: "账面原值不能为空", trigger: "change" }
          ],
        },
        id: null,
        type: 'add',
        point: [],
      }
    },
    created() {
      this.form.assetAddressProvince = '辽宁省'
      this.form.assetAddressCity = '沈阳市'
      this.id = this.$route.params && this.$route.params.id;
      this.type = this.$route.path.indexOf('/add') > -1 ? 'add' : this.$route.path.indexOf('/copy') > -1 ? 'copy' : 'edit'
      if (this.id) {
        getAssetInfo(this.id).then(r => {
          this.reset()
          if(r.code == 200) {
            this.form = {...r.data}
            this.point = [this.form.assetLon, this.form.assetLat]
          }
        })
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.getCity()
        setTimeout(this.getArea())
      })
    },
    methods: {
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.assetId != null) {
              if(this.type == 'edit') {
                updateAssetInfo(this.form).then(r => {
                  this.$message.success('修改成功！')
                  this.$tab.closePage()
                })
              } else {
                copyAssetInfo(this.form).then(r => {
                  this.$message.success('新增成功！')
                  this.$tab.closePage()
                })
              }
            } else if (this.type == 'add') {
              addAssetInfo(this.form).then(r => {
                this.$message.success('新增成功！')
                this.$tab.closePage()
              })
            }
          }
        });
      },
      // 表单重置
      reset() {
        this.form = {
          assetId: null,
          assetNumMaster: null,
          assetNumAttached: null,
          assetName: null,
          assetCustomNum: null,
          assetAddressProvince: '辽宁省',
          assetAddressCity: '沈阳市',
          assetAddressDistrict: null,
          assetLon: null,
          assetLat: null,
          assetDoorNum: null,
          assetUnitNum: null,
          assetRoomNum: null,
          assetHouseType: null,
          assetArea: null,
          assetOriginalValue: null,
          assetEstablishDate: null,
          assetOwnershipLength: null,
          assetPropertyUnit: null,
          assetStatus: null,
          assetImg: null,
          assetRemark: null,
          assetIsDelete: null,
          assetAddress: null
        };
        this.resetForm("form");
      },
      parseCnPostConsignee() {
        const address = this.consigneeText.trim();
        const regex = /^(.*?[省])?(.*?[市])(.*?[区]|.*?[县])(.*)$/;
        const match = address.match(regex);

        if (match) {
          console.log(match);
          this.$set(this.form, 'assetAddressProvince', match[1] || '')
          this.$set(this.form, 'assetAddressCity', match[2] || '')
          this.$set(this.form, 'assetAddressDistrict', match[3] || '')
          this.$set(this.form, 'assetAddress',  match[4] || '')
          this.$message.success('地址识别成功！');
        } else {
          this.$message.error('地址识别失败，请检查输入的地址格式是否正确');
        }
      },
      getCity() {
        this.cityLsit = this.proCityList.find(i => i.name == this.form.assetAddressProvince).children
      },
      getArea() {
        this.areaList = this.cityLsit.find(i => i.name == this.form.assetAddressCity).children
      },
      async clickAddress({address, addressComponents, point}) {
        if(addressComponents) {
          this.$set(this.form, 'assetAddressProvince', addressComponents.province)
          this.$set(this.form, 'assetAddressCity', addressComponents.city)
          this.$set(this.form, 'assetAddressDistrict', addressComponents.district)
          this.$set(this.form, 'assetAddress', addressComponents.street + addressComponents.streetNumber)
          await this.getCity()
          await this.getArea()
        }
        this.$set(this.form, 'assetLon', point.lng)
        this.$set(this.form, 'assetLat', point.lat)
      }
    }
  }
</script>

<style scoped lang="scss">
  .app-container {
    height: calc(100vh - 84px);
  }
.formC {
  width: 100%;
  padding: 0 50px;
  height: calc(100% - 60px);
  overflow-y: auto;
  .consignee {
    position: absolute;
    right: 10px;
    bottom: 10px;
  }
}
</style>
